package cat.joronya.supermanager.europeo.service;

import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.util.Log;

import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.market.Player;

/**
 * Donat l'HTML del llistat de mercat per posicio, el parsejem i
 * retornem els jugadors en VO's.
 * 
 * @author pol
 */
public class MarketBuyParser 
{
	private static final String TAG = "supermanager";
	
	// players new team XPATH
	private static final String PLAYERS_NEW_TEAM_XPATH = "//table";
	
	public ArrayList<Player> parse(String html, Integer jornada) throws Exception
	{
		ArrayList<Player> players = new ArrayList<Player>();
		
		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode node = cleaner.clean(html);
		
		// cerquem les jugadors
		Object[] table = node.evaluateXPath(PLAYERS_NEW_TEAM_XPATH);
		
		// si estan tancats els canvi, retorna pagina buida i no tenim players
		if( table.length == 0 )
			return null;
		
		TagNode tagTable = (TagNode)table[1];
		TagNode tagTbody = tagTable.getChildTags()[0];
		
		// llistem els jugados, diferents trs
		int i=0;
		for(Object objTr: tagTbody.getChildren())
		{
			// saltem tr, header
			if( i++ == 0 )
				continue;
			
			// els tds
			List<?> tds = ((TagNode)objTr).getChildren();
			
			// agafem el codi jugador i l'id per fer l'update
			String cod = null;
			String idJug = null;
			String playerName = "";
			String color = null;
			String team = null;
			String status = null;
			String nacionality = null;
			
			// segon element -> td lesionat
			TagNode td1 = (TagNode)tds.toArray()[1];
			TagNode imgStatus = null;
			for(Object td1Child: td1.getChildren())
			{
				imgStatus = (TagNode)td1Child;
				if ("img".equals(imgStatus.getName())) 
				{
					String src = imgStatus.getAttributeByName("src");
					if ("gif/lesion.gif".equals(src))
						status = "lesio.png";
					if ("gif/baja.gif".equals(src))
						status = "baixa.png";

					break;
				}
			}
			
			// tercer element -> td nacionality
			TagNode td2 = (TagNode)tds.toArray()[2];
			TagNode imgNacionalitat = null;
			for(Object t2Child: td2.getChildren())
			{
				imgNacionalitat = (TagNode)t2Child;
				if ("img".equals(imgNacionalitat.getName())) 
				{
					nacionality = imgNacionalitat.getAttributeByName("src").split("/")[1];
					nacionality = nacionality.split("\\.")[0];
					break;
				}
			}
			
			// quart element -> td
			TagNode td3 = (TagNode)tds.toArray()[3];
			TagNode fontPlayer = null;
			for(Object td3Child: td3.getChildren())
			{
				fontPlayer = (TagNode)td3Child;
				if( "font".equals(fontPlayer.getName()) )
				{
					color = fontPlayer.getAttributeByName("color");
					
					for(Object td3FontChild: fontPlayer.getChildren())
					{
						if( td3FontChild instanceof ContentNode )
						{
							ContentNode playerNode = (ContentNode)td3FontChild;
							playerName = playerNode.toString();
						}
					}
					break;
				}
			}
			
			// si tenim font i no es vermell o taronja, cerquem l'id_jug
			if( fontPlayer != null && !Supermanager.Market.RED_COLOR.equals(color.toUpperCase()) && 
				!Supermanager.Market.ORANGE_COLOR.equals(color.toUpperCase()) )
			{
				// nove element -> td del form, el HtmlCleaner formateja be i posa el td enlloc del form
				TagNode tdFormNode = (TagNode)tds.toArray()[8];

				// cerquem input de id_jug
				List<?> inputChilds = tdFormNode.getChildren();
				
				TagNode input = (TagNode)inputChilds.toArray()[1];
			
				// si es el element q toca
				if( input.getAttributeByName("name").equals("id_jug"))
					idJug = input.getAttributeByName("value");
			}
			else
			{
				// no comprable, posem el nom del jugador (codi) per fer update de
				// no comprable al postExecute
				idJug = playerName;
			}
			
			// sise element -> td
			TagNode td5 = (TagNode)tds.toArray()[5];
			TagNode aFont = null;
			for(Object td5Child: td5.getChildren())
			{
				aFont = (TagNode)td5Child;
				if( "font".equals(aFont.getName()) )
				{
					for(Object teamNode: aFont.getChildren())
					{
						if( teamNode instanceof ContentNode )
						{
							team = teamNode.toString();
							break;
						}
					}
				}
			}
			
			Log.d(TAG,"MarketBuyParser id_jug: "+idJug+", parsing code player: "+cod+", jornada: "+jornada);
			
			// creem player i el guardem per despres tractar-lo
			Player player = new Player();
			player.setDay(Integer.valueOf(jornada));
			player.setCodi(playerName);
			player.setName(playerName);
			player.setId(idJug);
			player.setTeam(team);
			player.setNacionality(nacionality+".png");
			player.setStatus(status);
			player.setShowInBuy(true);
			player.setColorInBuy(color);
			
			// guardem player al array list
			players.add(player);
		}
		
		return players;
	}
}
